package com.hejing.线程间通信与生产者消费者模型;

/**
 * ClassName: PrintNumberTest
 * Package: com.hejing.线程间通信与生产者消费者模型
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-04-15 11:40
 * @Version: 1.0
 */
public class PrintNumberTest {
    public static void main(String[] args) {
        PrintNumber p = new PrintNumber();
        Thread t1 = new Thread(p, "线程01");
        Thread t2 = new Thread(p, "线程02");

        t1.start();
        t2.start();

    }
}


class PrintNumber implements Runnable {

    private int number = 1;

    @Override
    public void run() {
        while (true) {
            synchronized(PrintNumber.class) {
                PrintNumber.class.notify();
                if (number <= 100) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ": " + number);
                    number++;

                    try {
                        PrintNumber.class.wait();  // 线程一旦执行此方法，就进入等待状态，同时，会释放同步监视器的调用(与sleep的区别)
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else break;
            }
        }
    }
}




























